import zipfile
import os
import datetime
import shutil
from loguru import logger
import pymysql
import zipfile
import json
import socket
import time

class err():
    def __init__(self,err_information):
        self.err_information = err_information

    def __call__(self,func):
        def wrap(*args,**kwargs):
            try:
                fun = func(*args,**kwargs)
                return fun
            except Exception as e:
                logger.debug(f'{self.err_information} wrong , the reason is {str(e)}')
        return wrap

class Db():
    def __init__(self,database_name):
        self.database_name = database_name

    def __enter__(self):
        self.conn = pymysql.connect(
        host='192.168.0.160',
        port=3306,
        user='root',
        passwd='lubanjianye',
        charset='utf8',
        database=self.database_name,
        cursorclass=pymysql.cursors.DictCursor)
        return self.conn

    def __exit__(self, exc_type, exc_val, exc_tb):
        logger.info(f'{exc_type}, {exc_val}, {exc_tb})')
        self.conn.close()

class log():
    def __init__(self,log_information):
        self.log_information = log_information

    def __call__(self,func):
        def wrap(*args,**kwargs):
            logger.info('{0} start...'.format(self.log_information))
            fun = func(*args,**kwargs)
            return fun
        return wrap

@log('compress')
@err('compress')
def compress(del_before = True,**compress_params):
    compress_path = compress_params['compress_path']
    compress_folder = compress_params['compress_folder']
    compress_to_path = compress_params['compress_to_path']
    if del_before in  compress_params:
        del_before = compress_params['del_before']

    #新压缩路径
    z = zipfile.ZipFile(os.path.join(compress_to_path,f'{compress_folder}_{datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d%H%M%S")}.zip'),'w')
    #将待压缩数据进行压缩
    for data in os.listdir(os.path.join(compress_path,compress_folder)):
        z.write(os.path.join(compress_path,compress_folder,data),data,zipfile.ZIP_DEFLATED)
    z.close()
    #删除原数据
    if del_before:
        if os.path.exists(os.path.join(compress_path,compress_folder)):
            shutil.rmtree(os.path.join(compress_path,compress_folder))


@log('readzip')
class Readzip():
    def __init__(self,path):
        self.path = path
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        with zipfile.ZipFile(self.path) as z:
            if self.index != len(z.namelist()):
                self.index += 1
                try:
                    return json.loads(z.read(z.namelist()[self.index - 1]).decode('utf-8'))
                except:
                    'json wrong'
            else:
                raise StopIteration


def iscompletezip(father_path):
    try:
        z = zipfile.ZipFile(father_path)
        z.close()
        return False
    except:
        logger.info('zip is not complete , the filr is {0}'.format(father_path))
        return True

@log('control')
def control(**params):
    report_interval_time = 1 * 60
    before_time = params['before_time']
    ip = params['ip']
    script = params['script']
    if not isinstance(before_time,datetime.date):
        before_time = datetime.datetime.strptime(before_time,"%Y-%m-%d %H:%M:%S")
    now_time = datetime.datetime.now()
    judge_interval = (now_time-before_time).seconds >= report_interval_time
    if judge_interval:
        with Db('tool') as conn:
            cursor = conn.cursor()
            sql = f'select update_time from control where ip = "{ip}" and script = "{script}"'
            cursor.execute(sql)
            report_update_time = cursor.fetchone()
            if report_update_time == None:
                sql = f'insert into control(ip,update_time,script,tag) values("{ip}","{datetime.datetime.now()}","{script}",0)'
                cursor.execute(sql)
                conn.commit()
            else:
                report_update_time = report_update_time['update_time']
                judge_interval = (now_time - report_update_time).seconds >= report_interval_time
                if judge_interval:
                    sql = f'update control set update_time = "{now_time}" ,tag = 0 where ip = "{ip}" and script = "{script}"'
                    cursor.execute(sql)
                    conn.commit()
        return datetime.datetime.now()
    return before_time

# params = {
#         'before_time': '2000-01-01 00:00:00',
#         'ip': socket.gethostbyname(socket.gethostname()),
#         'script': 'common.py'
#     }
# # while True:
# #     before_time = control(**params)
# #     print(before_time)
# #     params['before_time'] = before_time
# #     time.sleep(1)